#include "medicsmodel.h"
#include <QDebug>
MedicsModel::MedicsModel(QObject *parent) :
    QAbstractListModel(parent)
{

    QHash<int, QByteArray> roles;
    roles[DenominationRole] = "denomination";
    roles[FormeRole] = "forme";
    roles[CodeRole] = "code";

    setRoleNames(roles);

    mIsLoading = true;
}


int MedicsModel::rowCount(const QModelIndex &parent) const
{
    return mDatas.count();
}

QVariant MedicsModel::data(const QModelIndex &index, int role) const
{

    if(role== DenominationRole)
    {

        QString denomination =  mDatas.at(index.row()).value("dci").toString();



        return denomination;
    }

    if(role== FormeRole)
    {
        return mDatas.at(index.row()).value("forme").toString();
    }


    if ( role == CodeRole)
        return mDatas.at(index.row()).value("code").toString();


    return QVariant();

}

void MedicsModel::load(const QString &filter)
{


    QString q;

    if (filter.isEmpty())
        q ="SELECT DISTINCT dci FROM COMPO LIMIT 1,100";


    //q = "SELECT DISTINCT dci,FROM COMPO ";



    else
        q="SELECT DISTINCT dci FROM COMPO  WHERE dci LIKE '"+filter+"%' LIMIT 1,100";


    setQuery(q);




}

void MedicsModel::setQuery(const QString &q)
{

    setIsLoading(true);

    mDatas.clear();
    emit reset();
    QSqlQuery query(q); //la on peut definir la requette query ("SELECT dci FROM COMPO");
    while (query.next()) {
        beginInsertRows(QModelIndex(),0,0);
        mDatas.append(query.record());//remplir les donnees
        endInsertRows();


    }


    setIsLoading(false);
    qDebug()<<query.lastError();


}

void MedicsModel::setIsLoading(bool value)
{
    mIsLoading = value;
    emit isLoadingChanged();
}
